﻿namespace CleverCMS.Cms.Services.Infrastructure
{
    using MvcSiteMapProvider;
    using System;
    using System.Linq;
    using System.Collections.Generic;

    using Core.Infrastructure;

    public class AdminPagesDymanicNodeProvider : DynamicNodeProviderBase
    {
        private PageService         m_pagesService;
        private readonly AppCache   m_appCache;

        public AdminPagesDymanicNodeProvider()
        {
            this.m_appCache = new AppCache();
        }

        public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
        {
            if (m_appCache.Exists("AdminPages"))
                return (List<DynamicNode>)m_appCache.Get("AdminPages");

            m_pagesService = IoC.Get<PageService>();
            var nodes = new List<DynamicNode>();

            var pages = m_pagesService.LoadAll();
            foreach (var page in pages)
            {
                var pageNode = new DynamicNode { Key = "page_" + Guid.NewGuid(), Title = page.PageTitle };
                pageNode.RouteValues.Add("id", page.Id);
                pageNode.Action = "Edit";
                pageNode.Controller = "Page";
                pageNode.Area = "CleverCms.Admin" ;
                nodes.Add(pageNode);
            }

            m_appCache.Add("AdminPages", nodes);
            return nodes;
        }
    }
}
